package org.apache.lucene.ocean;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

import org.apache.commons.io.FileUtils;
import org.apache.lucene.ocean.util.OceanRandomAccessFile;
import org.apache.lucene.ocean.util.Util;

public class FSLogDirectory extends LogDirectory {
  private File fileDirectory;
  private ReentrantLock outputLock = new ReentrantLock();
  private ReentrantLock inputLock = new ReentrantLock();

  public FSLogDirectory(File fileDirectory) {
    Util.mkdir(fileDirectory);
    this.fileDirectory = fileDirectory;
  }
  
  public String[] list() throws IOException {
    List<String> list = new ArrayList<String>();
    for (File file : fileDirectory.listFiles()) {
      if (!file.isDirectory()) {
        list.add(file.getName());
      }
    }
    return (String[]) list.toArray(new String[0]);
  }

  public boolean fileExists(String name) throws IOException {
    File file = new File(fileDirectory, name);
    return file.exists();
  }

  public long fileModified(String name) throws IOException {
    File file = new File(fileDirectory, name);
    return file.lastModified();
  }

  public boolean deleteFile(String name) throws IOException {
    File file = new File(fileDirectory, name);
    if (file.isDirectory()) {
      FileUtils.deleteDirectory(file);
      return file.exists();
    } else {
      boolean deleted = file.delete();
      return deleted;
    }
    //if (!deleted) {
      //throw new IOException("file: "+name+" not deleted");
    //}
  }

  public long fileLength(String name) throws IOException {
    File file = new File(fileDirectory, name);
    return file.length();
  }

  public OceanRandomAccessFile openInput(String name) throws IOException {
    inputLock.lock();
    try {
      File file = new File(fileDirectory, name);
      return new OceanRandomAccessFile(file, "r");
    } finally {
      inputLock.unlock();
    }
  }

  public OceanRandomAccessFile getOutput(String name, boolean overwrite) throws IOException {
    outputLock.lock();
    try {
      File file = new File(fileDirectory, name);
      if (overwrite) {
        file.delete();
      }
      return new OceanRandomAccessFile(file, "rw");
    } finally {
      outputLock.unlock();
    }
  }
}
